package cn.yedong.basic.controller;

import cn.yedong.basic.util.AjaxResult;
import cn.yedong.basic.util.FastDfsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Api(value ="文件上传接口",description = "处理文件上传和删除的操作")
@RestController
@RequestMapping("fastDfs")
public class FastDfsController {
    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation("接口：文件上传")
    @PostMapping
    public AjaxResult uploadFile(@RequestPart MultipartFile file){
        try {
            //获取原始文件名,xx.png
            String originalFilename = file.getOriginalFilename();
            //获取文件扩展名 png
            String exeName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //调用工具类上传图片
            //byte[] bytes = file.getBytes();将文件内容转换成一个byte数组
            //上传文件后返回文件名/group1/M00/03/8B/CgAIC2PeJFSAG_U3AD903OP41Wk022.jpg
            //报错：字段文件超过其允许的最大大小1048576字节：10MB
            String fileName = FastDfsUtils.upload(file.getBytes(), exeName);

            //链式语法：上传成功将文件名返回给前端
            return AjaxResult.me().setObj(fileName);

        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }

    /**
     * 文件删除
     * delete http://localhost:8080/fastDfs?path=/group1/M00/03/8B/CgAIC2PeJFSAG_U3AD903OP41Wk022.jpg
     * @param path
     * @return
     */
    @ApiOperation("接口：文件删除")
    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam String path){
        try {
            //path=/group1/M00/03/8B/CgAIC2PeJFSAG_U3AD903OP41Wk022.jpg
            path = path.substring(1);//group1/M00/03/8B/CgAIC2PeJFSAG_U3AD903OP41Wk022.jpg
            //获取组名
            String groupName = path.substring(0, path.indexOf("/"));//group1
            //获取文件名
            String fileName = path.substring(path.indexOf("/") + 1);//M00/03/8B/CgAIC2PeJFSAG_U3AD903OP41Wk022.jpg
            //调用工具类删除
            FastDfsUtils.delete(groupName,fileName);
            //返回前端处理结果
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败！");
        }
    }
}
